package bean;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;

import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebFilter;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import Model.HoaDon;
import Model.NhaSanXuat;
import Model.SanPham;
import Util.DAO;
import Util.Util;

@ManagedBean(name="beanSanPham")
@SessionScoped
public class BeanSanPham implements Serializable{
	
	private String ten;
	private BigInteger gia;
	
	private String cpu;
	private String ram;
	private String hdd;
	private String manHinh;
	private String doHoa;
	private String oDia;
	private String wifi;
	private String webcam;
	private String pin;
	private String hdh;
	private String hinh;
	private String baoHanh;
	private String khuyenMai;
	private UploadedFile fileUpload;
	private ArrayList<SanPham> danhSachSanPham=new ArrayList<SanPham>();
	private ArrayList<SanPham> danhSachSanPham1=new ArrayList<SanPham>();	
	private boolean trung;
	private SanPham sanpham;
	private boolean capnhat;
	private NhaSanXuat nsx;
	private int back;
	private boolean dkhd = true;
	
	public boolean isDkhd() {
		return dkhd;
	}
	public void setDkhd(boolean dkhd) {
		this.dkhd = dkhd;
	}
	public int getBack() {
		return back;
	}
	public void setBack(int back) {
		this.back = back;
	}
	public boolean isCapnhat() {
		return capnhat;
	}
	public void setCapnhat(boolean capnhat) {
		this.capnhat = capnhat;
	}
	public String getBaoHanh() {
		return baoHanh;
	}
	public void setBaoHanh(String baoHanh) {
		baoHanh = baoHanh.trim();
		this.baoHanh = baoHanh;
	}
	
	public NhaSanXuat getNsx() {
		return nsx;
	}
	public void setNsx(NhaSanXuat nsx) {
		this.nsx = nsx;
	}
	
	public SanPham getSanpham() {
		return sanpham;
	}
	public void setSanpham(SanPham sanpham) {
		this.sanpham = sanpham;
	}
	public ArrayList<SanPham> getDanhSachSanPham() {
		return danhSachSanPham;
	}
	public ArrayList<SanPham> getDanhSachSanPham1() {
		return danhSachSanPham1;
	}
	
	public String getTen() {
		return ten;
	}
	public void setTen(String ten) {
		ten = ten.trim();
		this.ten = ten;
	}
	public BigInteger getGia() {
		return gia;
	}
	public void setGia(BigInteger gia) {
		this.gia = gia;
	}
	public String getCpu() {
		return cpu;
	}
	public void setCpu(String cpu) {
		cpu = cpu.trim();
		this.cpu = cpu;
	}
	public String getRam() {
		return ram;
	}
	public void setRam(String ram) {
		ram = ram.trim();
		this.ram = ram;
	}
	public String getHdd() {
		return hdd;
	}
	public void setHdd(String hdd) {
		hdd = hdd.trim();
		this.hdd = hdd;
	}
	public String getManHinh() {
		return manHinh;
	}
	public UploadedFile getFileUpload() {
		return fileUpload;
	}
	public void setFileUpload(UploadedFile fileUpload) {
		this.fileUpload = fileUpload;
	}
	public void setManHinh(String manHinh) {
		
		this.manHinh = manHinh;
	}
	public String getDoHoa() {
		return doHoa;
	}
	public void setDoHoa(String doHoa) {
		doHoa = doHoa.trim();
		this.doHoa = doHoa;
	}
	public String getoDia() {
		return oDia;
	}
	public void setoDia(String oDia) {
		oDia = oDia.trim();
		this.oDia = oDia;
	}
	public String getWifi() {
		return wifi;
	}
	public void setWifi(String wifi) {
		wifi = wifi.trim();
		this.wifi = wifi;
	}
	public String getWebcam() {
		return webcam;
	}
	public void setWebcam(String webcam) {
		webcam = webcam.trim();
		this.webcam = webcam;
	}
	public String getPin() {
		return pin;
	}
	public void setPin(String pin) {
		pin = pin.trim();
		this.pin = pin;
	}
	public String getHdh() {
		return hdh;
	}
	public void setHdh(String hdh) {
		hdh = hdh.trim();
		this.hdh = hdh;
	}
	public String getHinh() {
		return this.fileUpload.getFileName();
	}
	public void setHinh(String hinh) {
		this.hinh = hinh;
	}
	public String getKhuyenMai() {
		return khuyenMai;
	}
	public void setKhuyenMai(String khuyenmai) {
		khuyenmai = khuyenmai.trim();
		this.khuyenMai = khuyenmai;
	}
	
//	public void handleFileUpload(FileUploadEvent event) {
//       setFileUpload(event.getFile());
//       System.out.println("event: "+event.getFile().getFileName());
//       System.out.println("file upload: "+this.getFileUpload().getFileName());
//       System.out.println("file upload: "+fileUpload.getFileName());
//	}
	public void upload() {
        if(fileUpload != null) {  
            try {     	
            	this.setHinh(new String(ten.getBytes("ISO-8859-1"), "UTF-8")+".jpg");
				copyFile(ten);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        else{
        	if(!capnhat){
        	 this.setHinh("hinhmacdinh.jpg");
        	}
        }
    }
    
    private void copyFile(String fileName) {
		try {
			ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        	String folder = ctx.getRealPath("/resources/images/hinhsanpham/");
        	BufferedImage originalImage = ImageIO.read(fileUpload.getInputstream());
			int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
	 
			BufferedImage resizeImageJpg = Util.resizeImage(originalImage, type);
			ImageIO.write(resizeImageJpg, "jpg", new File(folder+"/"+fileName+".jpg")); 

		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
    }
    
    public void kiemtratrung(){
    	SanPham sp = DAO.kiemtrasanpham(ten);
    	if(sp != null){
    		boolean dkhd1 = true;
    		Set<HoaDon> dshd = sp.getDshd();
    		for (HoaDon hoaDon : dshd) {
				if(!hoaDon.isDathanhtoan()){
					 dkhd1 = false;
					 break;
				}
			}
    		if(dkhd1){
    	FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Tên sản phẩm đã tồn tại", "thông tin sẽ được cập nhật!"));
    		}
    		else{
    			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Tên sản phẩm nằm trong hóa đơn chưa thanh toán","không thể ghi nhận thông tin của sản phẩm này"));		
    		}
    	}
    	}
    public void kiemtratrung1(){
    	try {
			ten = new String(ten.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	SanPham sp = DAO.kiemtrasanpham(ten);
    	if(sp != null){
    		Set<HoaDon> dshd = sp.getDshd();
    		for (HoaDon hoaDon : dshd) {
				if(!hoaDon.isDathanhtoan()){
					 dkhd = false;
					 break;
				}
			}
    	trung = true;
    	}else{
    	trung = false;
    	}
    }
	public String luusanpham(){
		kiemtratrung1();
		if(!dkhd){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Tên sản phẩm nằm trong hóa đơn chưa thanh toán","không thể ghi nhận thông tin của sản phẩm này"));
			dkhd = true;
			return null;
		}
		NhaSanXuat nsx1 = DAO.laynhasanxuat(this.nsx.getIdnhasanxuat());
		if(nsx1 == null){
			DAO.luunhasanxuat(nsx);
		}
		try {
			cpu = new String(cpu.getBytes("ISO-8859-1"),"utf-8");
			ram = new String(ram.getBytes("ISO-8859-1"),"utf-8");
			hdd = new String(hdd.getBytes("ISO-8859-1"),"utf-8");
			manHinh = new String(manHinh.getBytes("ISO-8859-1"),"utf-8");
			doHoa = new String(doHoa.getBytes("ISO-8859-1"),"utf-8");
			oDia = new String(oDia.getBytes("ISO-8859-1"),"utf-8");
			wifi = new String(wifi.getBytes("ISO-8859-1"),"utf-8");
			webcam = new String(webcam.getBytes("ISO-8859-1"),"utf-8");
			pin = new String(pin.getBytes("ISO-8859-1"),"utf-8");
			hdh = new String(hdh.getBytes("ISO-8859-1"),"utf-8");
			baoHanh = new String(baoHanh.getBytes("ISO-8859-1"),"utf-8");
			khuyenMai = new String(khuyenMai.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SanPham sp = new SanPham(ten,gia,cpu,ram,hdd,manHinh,doHoa,oDia,wifi,webcam,pin,hdh,hinh,khuyenMai,baoHanh);
		sp.setNhasanxuat(nsx);
	
		if(!trung){
		danhSachSanPham.add(sp);
		danhSachSanPham1 = (ArrayList<SanPham>) danhSachSanPham.clone();
		Collections.reverse(danhSachSanPham1);
	DAO.luusanpham(sp);
		}
		else{
				System.out.println(danhSachSanPham.remove(getSanpham()));
				danhSachSanPham.add(sp);
				danhSachSanPham1 = (ArrayList<SanPham>) danhSachSanPham.clone();
				Collections.reverse(danhSachSanPham1);
		DAO.capnhat(sp);
		}
		
		setFileUpload(null);
		setNsx(new NhaSanXuat());
		setCpu("");
		setDoHoa("");
		setFileUpload(null);
		setGia(null);
		setHdd("");
		setHdh("");
		setHinh("");
		setKhuyenMai("");
		setManHinh("");
		setoDia("");
		setPin("");
		setRam("");
		
		setTen("");
		setWebcam("");
		setWifi("");
		setBaoHanh("");
		setBack(0);
		capnhat = false;
		return null;
	}
	
	public String capnhatsanpham(){
		System.out.println("cap nhat san pham");
		NhaSanXuat nsx1 = DAO.laynhasanxuat(this.nsx.getIdnhasanxuat());
		if(nsx1 == null){
			DAO.luunhasanxuat(nsx);
		}
		try {
			cpu = new String(cpu.getBytes("ISO-8859-1"),"utf-8");
			ram = new String(ram.getBytes("ISO-8859-1"),"utf-8");
			hdd = new String(hdd.getBytes("ISO-8859-1"),"utf-8");
			manHinh = new String(manHinh.getBytes("ISO-8859-1"),"utf-8");
			doHoa = new String(doHoa.getBytes("ISO-8859-1"),"utf-8");
			oDia = new String(oDia.getBytes("ISO-8859-1"),"utf-8");
			wifi = new String(wifi.getBytes("ISO-8859-1"),"utf-8");
			webcam = new String(webcam.getBytes("ISO-8859-1"),"utf-8");
			pin = new String(pin.getBytes("ISO-8859-1"),"utf-8");
			hdh = new String(hdh.getBytes("ISO-8859-1"),"utf-8");
			baoHanh = new String(baoHanh.getBytes("ISO-8859-1"),"utf-8");
			khuyenMai = new String(khuyenMai.getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SanPham sp = new SanPham(ten,gia,cpu,ram,hdd,manHinh,doHoa,oDia,wifi,webcam,pin,hdh,hinh,khuyenMai,baoHanh);
		sp.setNhasanxuat(nsx);
		if(!danhSachSanPham.contains(sp)){
			System.out.println("san pham bi remove 1");
			danhSachSanPham.add(sp);
			danhSachSanPham1 = (ArrayList<SanPham>) danhSachSanPham.clone();
			Collections.reverse(danhSachSanPham1);
		}
		else{
			System.out.println("san pham bi remove 2");
			System.out.println(danhSachSanPham.remove(getSanpham()));
			danhSachSanPham.add(sp);
			danhSachSanPham1 = (ArrayList<SanPham>) danhSachSanPham.clone();
			Collections.reverse(danhSachSanPham1);
		}
		
		setFileUpload(null);
		setNsx(new NhaSanXuat());
		setCpu("");
		setDoHoa("");
		setFileUpload(null);
		setGia(null);
		setHdd("");
		setHdh("");
		setHinh("");
		setKhuyenMai("");
		setManHinh("");
		setoDia("");
		setPin("");
		setRam("");

		setTen("");
		setWebcam("");
		setWifi("");
		setBaoHanh("");
		setBack(0);
		capnhat = false;
		return null;
	}
	public String chitiet(){
		setFileUpload(null);
		setNsx(sanpham.getNhasanxuat());
		setCpu(sanpham.getCpu());
		setDoHoa(sanpham.getDoHoa());
		setGia(sanpham.getGia());
		setHdd(sanpham.getHdd());
		setHdh(sanpham.getHdh());
		setHinh(sanpham.getHinh());
		setKhuyenMai(sanpham.getKhuyenMai());
		setManHinh(sanpham.getManHinh());
		setoDia(sanpham.getoDia());
		setPin(sanpham.getPin());
		setRam(sanpham.getRam());
	
		setTen(sanpham.getTen());
		setWebcam(sanpham.getWebcam());
		setWifi(sanpham.getWifi());
		setBaoHanh(sanpham.getBaoHanh());
		setBack(this.back-1);
		capnhat = true;
		return null;
	}
	public List<String> complete(String query){
		List<NhaSanXuat> l = DAO.laytatcanhasanxuat();
		List<String> ketqua = new ArrayList<String>();
		query = query.trim().toLowerCase();
		for (NhaSanXuat nsx : l) {
			String ten = nsx.getTennhasanxuat();
			ten = ten.trim().toLowerCase();
			if(ten.contains(query)){
			ketqua.add(nsx.getTennhasanxuat());
			}
		}
		return ketqua;
	}
	public String quaylai(){
		setFileUpload(null);
		setNsx(new NhaSanXuat());
		setCpu("");
		setDoHoa("");
		setFileUpload(null);
		setGia(null);
		setHdd("");
		setHdh("");
		setHinh("");
		setKhuyenMai("");
		setManHinh("");
		setoDia("");
		setPin("");
		setRam("");
		
		setTen("");
		setWebcam("");
		setWifi("");
		setBaoHanh("");
		setBack(0);
		capnhat = false;
		return null;
	}
	public String xoasanpham(){
		DAO.xoasanpham(getSanpham());
		danhSachSanPham.remove(getSanpham());
		danhSachSanPham1 = (ArrayList<SanPham>) danhSachSanPham.clone();
		Collections.reverse(danhSachSanPham1);
		
		setNsx(new NhaSanXuat());
		setCpu("");
		setDoHoa("");
		setFileUpload(null);
		setGia(null);
		setHdd("");
		setHdh("");
		setHinh("");
		setKhuyenMai("");
		setManHinh("");
		setoDia("");
		setPin("");
		setRam("");
	
		setTen("");
		setWebcam("");
		setWifi("");
		setBaoHanh("");
		setBack(0);
		capnhat = false;
		return null;
	}
	public String logout() {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "dangnhap.xhtml?faces-redirect=true";
    }

}
